<template>
    <div id="myMain">
        <div class="myMain-padding picture-main displayFlexR">
            <div class="left boxShadow paddingSize">
                <p class="baseBG" style="padding: 10px;">全部表单<i class="el-icon-plus fr" style="line-height: 20px;" @click="addAlert(null)"></i></p>
                <el-tree
                :highlight-current="true"
                :data="treeData"
                :props="defaultProps"
                accordion
                node-key="id"
                :default-expanded-keys="[1]"
                :expand-on-click-node="false"
                :default-expand-all="true"
                @node-click="classification">
                    <span class="custom-tree-node" slot-scope="{ data }" style="width: 100%;line-height: 20px;">
                    <span style="display: inline-block;width: 120px;white-space : nowrap;overflow : hidden;text-overflow : ellipsis;line-height: 30px;">{{ data.name }}</span>
                    <el-switch v-if="data.fatherId != '-1'" v-model="data.status" :active-value="1" :inactive-value="0" :width="30" class="fr" @change="changeEvent(data)" style="height: 30px;line-height: 30px;margin-left: 10px;"></el-switch>
                    <el-button v-if="data.fatherId == '-1'" @click="addAlert(data)" size="mini" type="text" icon="el-icon-plus" style="font-size: 20px;padding:0px;width: 30px;margin-left: 10px;" class="fr"></el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" class="fr" style="margin-left: 10px;" @click="delName(data)"></el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" class="fr" @click="editName(data)"></el-button>
                </span>
                </el-tree>
            </div>
            <div class="right paddingSize displayFlexC">
                <div v-show="triggerVal != ''">
                    <vxe-button icon="fa fa-plus" @click="insertEvent(-1)" style="width: 15vh;margin-bottom: 1%;" class="fl">新增</vxe-button>
                    <vxe-button icon="fa fa-delete" @click="$refs.xTable.removeCheckboxRow()">删除选中</vxe-button>
                    <vxe-button icon="fa fa-save" @click="saveEvent()" style="width: 15vh;margin-bottom: 1%;" class="fl">保存</vxe-button>
                </div>
                <vxe-table
                border
                show-overflow
                align="center"
                ref="xTable"
                :data="tableData"
                :edit-rules="validRules"
                :edit-config="{trigger: triggerVal, mode: 'cell', icon: 'fa fa-pencil'}"
                @checkbox-all="selectAllEvent"
                @checkbox-change="selectChangeEvent"
                :checkbox-config="{reserve: true}">
                <vxe-table-column type="checkbox" width="60" v-if="triggerVal != ''"></vxe-table-column>
                <vxe-table-column type="seq" title="序号"  width="60"></vxe-table-column>
                <!-- <vxe-table-column field="name" title="字段名" :edit-render="{name: 'input', defaultValue: null}"></vxe-table-column> -->
                <vxe-table-column field="remark" title="中文字段名" :edit-render="{name: 'input', defaultValue: null}"></vxe-table-column>
                <vxe-table-column field="type" title="数据类型" :edit-render="{name: '$select', options: typeList, defaultValue: null}">
                    <template #default="{ row }">
                        <span v-if="row.type == 'varchar' || row.type == 0">文本</span>
                        <span v-else-if="row.type == 'int' || row.type == 1">数字</span>
                        <span v-else-if="row.type == 'date' || row.type == 2">日期</span>
                        <span v-else>未知</span>
                    </template>
                </vxe-table-column>
                </vxe-table>
            </div>
        </div>
        <vxe-modal v-model="alertVal1" :title="alertTitle1" width="20%">
            <template #default>
                <vxe-form
                title-colon
                ref="xForm1"
                title-align="right"
                title-width="130"
                :data="addFormData1"
                :rules="formRules1"
                @submit="submitEvent1"
                @reset="resetEvent">
                    <vxe-form-item title="名称" field="name" span="24" :item-render="{}" title-overflow="title">
                        <template #default="params">
                            <vxe-input v-model="params.data.name" placeholder="请输入名称" clearable @input="$refs.xForm1.updateStatus(params)"></vxe-input>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item align="center" :item-render="{}">
                        <template #default>
                        <vxe-button type="submit" status="primary">提交</vxe-button>
                        <vxe-button type="reset">重置</vxe-button>
                        </template>
                    </vxe-form-item>
                </vxe-form>
            </template>
        </vxe-modal>
        <vxe-modal v-model="alertVal2" title="选择需要填报表单的企业" width="80%" height="60%" showFooter @confirm="confirmEvent()">
            <template #default>
                <vxe-table
                ref="xTable2"
                :filter-config="{showIcon: false}"
                border
                align="center"
                highlight-hover-row
                :data="tableData2"
                :export-config="{}"
                @checkbox-all="selectAllEvent"
                @checkbox-change="selectChangeEvent"
                row-id="id"
                :seq-config="{startIndex: (tablePage2.currentPage - 1) * tablePage2.pageSize}"
                :checkbox-config="{reserve: true}">
                <vxe-table-column type="checkbox" width="60"></vxe-table-column>
                <vxe-table-column type="seq" title="序号" width="100"></vxe-table-column>
                <vxe-table-column field="fname" title="企业名称"></vxe-table-column>
                <vxe-table-column field="corp" title="企业法人"></vxe-table-column>
                <vxe-table-column field="nid" title="身份证号"></vxe-table-column>
                <vxe-table-column field="phone" title="联系方式"></vxe-table-column>
                <vxe-table-column field="email" title="联系邮箱"></vxe-table-column>
                </vxe-table>
                <!-- 分页 -->
                <vxe-pager
                perfect
                size="mini"
                :current-page="tablePage2.currentPage"
                :page-size="tablePage2.pageSize"
                :page-sizes="tablePage2.pageSizes"
                :total="tablePage2.totalResult"
                @page-change="pageChange"
                :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total']">
                </vxe-pager>
            </template>
        </vxe-modal>
    </div>
</template>
<style lang="scss" scoped>
@import '../../styles/all.scss';
::v-deep.vxe-form .vxe-form--item:last-of-type{
  margin: 0 auto;
    display: flow-root;
}
#myMain{
    .picture-main{
        flex: 1;
        .left{
            width: 300px;
            p:nth-of-type(1){
                text-align: center;
                border-radius: 5px;
                margin: 0 0 20px 0;
            }
        }
        .right{
            width: calc(100% - 300px);
            flex: 1;
        }
    }
}
</style>
<script>
import { getFormClassification, addFormClassification, addFormInfo, getFormInfoById, putFormInfoByStatus,delClassOrFormName,putClassOrFormName,putFormInfoByStatus1 } from '@/api/Data_filling'
import { getFirmInfoBypaStatus  } from '@/api/enterprise_Manage'
export default {
    props: {
    },
    components:{
    },
    data(){
        const nameValid = ({ cellValue }) => {
            // 模拟服务端校验
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (!cellValue){
                        reject(new Error('请填写字段名！'))
                    }else if (!/[a-z]|[A-Z]/.test(cellValue)){
                        reject(new Error('字段名为英文大小写字符组成！'))
                    }else if ((cellValue.length < 3 || cellValue.length > 50)) {
                        reject(new Error('字段名长度在 3 到 50 个字符之间'))
                    } else {
                        resolve()
                    }
                }, 100)
            })
        }
        return{
            // 当前表的id
            currentId: null,
            statusObj: null,
            // 添加表单和具体表
            alertVal1: false,
            alertTitle1: '添加分类名称',
            addFormData1: {
                fatherId: '-1',
                name: '',
                status: 0
            },
            formRules1: {
                name: [
                    { required: true, message: '请输入名称' },
                ]
            },
            // 树形控件
            treeData: [],
            defaultProps: {
                children: 'children',
                name: 'name'
            },
            activeVal: null,
            // 插入表
            tableData: [],
            list: [
                { id: 1, name: 'firmName', type: 0, remark: '公司名称' }
            ],
            typeList: [
                { label: '文本', value: 0 },
                { label: '数字', value: 1 },
                { label: '日期', value: 2 }
            ],
            validRules: {
                type: [
                  { required: true, message: '类型必须填写' }
                ],
                remark: [
                  { required: true, message: '中文字段名必须填写' }
                ]
            },
            // 有表数据旧不可以编辑
            triggerVal: '',
            // 弹窗-选择下发的企业
            alertVal2: false,
            tableData2: [],
            // 分页
            tablePage2: {
                currentPage: 1,
                pageSize: 8,
                pageSizes: [8, 16, 24, 32],
                totalResult: 0
            },
            checkedBoxList: [],
        }
    },
    watch:{
    },
    methods:{
        // 添加
        addAlert(data){
            this.alertVal1 = true
            if(data == null){
                this.alertTitle1 = '添加分类名称'
            }else{
                this.alertTitle1 = '添加表单名称'
                this.addFormData1.fatherId = data.id
            }
        },
        // 弹窗
        submitEvent1(){
            if(this.addFormData1.fatherId == '-1'){
                // 分类
                if(this.alertTitle1 == '修改分类名称'){
                    this.edit(this.addFormData1.id, this.addFormData1.name)
                }else{
                    this.addFormData1.fatherId == '-1'
                    this.add(this.addFormData1)
                }
            }else{
                // 表单
                if(this.alertTitle1 == '修改表单名称'){
                    this.edit(this.addFormData1.id, this.addFormData1.name)
                }else{
                    this.addFormData1.fatherId == null
                    this.add(this.addFormData1)
                }
            }
            
        },
        edit(id, name){
            putClassOrFormName(id, name).then(res => {
                // console.log("修改表", res)
                if(res.resp_code == 0){
                    this.$XModal.message({ status: 'success', content: '修改成功！' })
                    this.alertVal1 = false
                    this.getForm()
                }
            })
        },
        add(data){
            addFormClassification(data).then(res => {
                // console.log("add class res", res)
                if(res.resp_code == 0){
                    this.alertVal1 = false
                    this.addFormData1.name = ''
                    this.$XModal.message({ status: 'success', content: '添加成功！' })
                    this.getForm()
                }
            })
        },
        resetEvent () {
            this.$XModal.message({ message: '重置表单内容!', status: 'info' })
        },
        getFormInfo(id){
            // 查询单个表单
            getFormInfoById(id).then(res => {
                // console.log("单个表单", res)
                if(res.length == 0){
                    // 无表数据
                    this.triggerVal = 'click'
                    this.tableData = this.list
                }else{
                    this.triggerVal = ''
                    this.tableData = res
                    this.currentId = res.id
                }
                this.$refs.xTable.clearCheckboxRow()
            })
        },
        // 根据分类筛选表内容
        classification(rowData){
            // console.log('row data', rowData)
            if(rowData.fatherId == '-1'){
                // 一级
                console.log('这里是一级')
            }else{
                // 二级
                this.activeVal = rowData
                this.getFormInfo(rowData.id)
            }
        },
        // insert form data
        async insertEvent (row) {
            const $table = this.$refs.xTable
            const record = {
                type: 0
            }
            const { row: newRow } = await $table.insertAt(record, row)
            await $table.setActiveCell(newRow, 'type')
        },
        // save form data
        async saveEvent(){
            // 选择表名再保存
            if(this.activeVal != null){
                const $table = this.$refs.xTable
                const errMap = await $table.validate().catch(errMap => errMap)
                if (errMap) {
                    this.$XModal.message({ status: 'error', content: '校验不通过！' })
                } else {
                    // let fieldList = []
                    let typeList = []
                    let remarkList = []
                    let saveObj = { typeList, remarkList}
                    const { insertRecords } = $table.getRecordset()
                    let newTableData = [...this.tableData, ...insertRecords]
                    newTableData.forEach(ele => {
                        // saveObj.fieldList.push(ele.name)
                        saveObj.typeList.push(ele.type)
                        saveObj.remarkList.push(ele.remark)
                    })
                    let dataInfo = {...this.activeVal, ...saveObj}
                    addFormInfo(dataInfo).then(res => {
                        // console.log("add form res", res)
                        if(res.resp_code == 0){
                            this.$XModal.message({ status: 'success', content: '保存表单成功！' })
                            this.activeVal = null
                            this.getFormInfo(2)
                        }
                    })
                    
                }
            }else{
                 this.$XModal.message({ status: 'error', content: '请选择左边表名！' })
            }
        },
        // get form classification
        getForm(){
            getFormClassification().then(res => {
                console.log("form classification", res)
                this.treeData = res.data
            })
        },
        // 改变状态
        changeEvent(row){
            console.log("row", row)
            this.statusObj ={ id: row.id, status: row.status}
            if( row.status == 1){
                this.alertVal2 = true
            }else{
                //关闭
                putFormInfoByStatus1(this.statusObj.id , this.statusObj.status).then(res => {
                    if(res.resp_code == 0){
                        this.getForm()
                    }
                })
            }
            
            
        },
        // 修改/删除分类名称 表
        editName(data){
            if(data.fatherId == '-1'){
                this.alertTitle1 = '修改分类名称'
            }else{
                this.alertTitle1 = '修改表单名称'
            }
            this.alertVal1 = true
            this.addFormData1 = data
        },
        delName(data){
            this.$confirm('是否删除该分类/表单?', '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delClassOrFormName(data.id, data.name).then(res => {
                    // console.log("删除表", res)
                    if(res.resp_code == 0){
                        this.$XModal.message({ status: 'success', content: '删除成功！' })
                        this.getForm()
                    }
                })
            })
        },
        // 根据页切换
        pageChange(val){
            console.log('page val', val)
            this.tablePage2.currentPage = val.currentPage
            let page = val.currentPage
            let limit = val.pageSize
            this.initFirm(page, limit)
        },
        selectAllEvent ({ checked, records }) {
            this.checkedBoxList = records
            // 全选
            console.log(checked ? '所有勾选事件' : '所有取消事件', records)
        },
        selectChangeEvent ({ checked, records }) {
            this.checkedBoxList = records
            // 单选个
            console.log(checked ? '勾选事件' : '取消事件', records)
        },
        initFirm(page, limit){
            getFirmInfoBypaStatus(page, limit, 1, 2).then(res => {
                console.log('qiye xinxi', res)
                this.tableData2 = JSON.parse(JSON.stringify(res.data))
                this.tablePage2.totalResult = res.count
            })
        },
        // 选择下发企业
        confirmEvent(){
            if(this.checkedBoxList.length != 0){
                this.$XModal.message({ message: '已选择' + this.checkedBoxList.length + '家企业下发表单!', status: 'success' })
                let firmList = []
                for (let i=0; i<this.checkedBoxList.length; i++) {
                    firmList.push(this.checkedBoxList[i].fid)
                }
                firmList = firmList.join(",")
                this.statusObj['firmList'] = firmList
                putFormInfoByStatus(this.statusObj.id, this.statusObj.firmList, this.statusObj.status).then(res => {
                    console.log("修改状态", res)
                    if(res.resp_code == 0){
                        this.$refs.xTable2.clearCheckboxRow()
                        this.getForm()
                    }
                })
            }else{
                this.$XModal.message({ message: '请选择需要下发的企业!', status: 'info' })
            }
        }
        
        
    },
    created(){},
    mounted(){
        this.getForm()
        this.getFormInfo(2)
        this.initFirm(this.tablePage2.currentPage, this.tablePage2.pageSize)
    },
}
</script>